package org.chen.mybatis.parameter;

import java.util.ArrayList;
import java.util.List;

/**
 * 参数映射
 *
 * @author Chen
 * @since 2023/6/9 12:10
 */
public class ParameterMapping {

    /**
     * 转换后的Sql
     */
    private final String sql;

    private List<String> paramMapping;

    public ParameterMapping(String sql) {
        this.sql = parseSql(sql);
    }

    public String getSql() {
        return sql;
    }

    public List<String> getParamMapping() {
        return paramMapping;
    }

    private String parseSql(String sql) {
        paramMapping = new ArrayList<>();
        //将sql转换为字符数组
        char[] charArray = sql.toCharArray();
        //临时sql
        String tempSql = sql;
        //参数起始位置
        int startIndex = 0;
        //参数结束位置
        int endIndex;
        for (int i = 0; i < charArray.length; i++) {
            char c = charArray[i];
            String s = String.valueOf(c);
            //判断是否是起始参数
            if ("#".equals(s)) {
                startIndex = i;
            }
            //判断是否是结束参数
            if ("}".equals(s)) {
                endIndex = i;
                if (endIndex > startIndex) {
                    int tempLength = sql.length() - tempSql.length();
                    startIndex -= tempLength;
                    endIndex -= tempLength;
                    String substring = tempSql.substring(startIndex + 2, endIndex);
                    tempSql = tempSql.replace("#{" + substring + "}", "?");
                    paramMapping.add(substring);
                }
            }
        }
        return tempSql;
    }
}
